import router, { asyncRoutes } from '@/router'
import store from '@/store'
// 导入进度条
import nProgress from 'nprogress'
// 导入进度条样式
import 'nprogress/nprogress.css'
// 导入设置标题函数
import getPageTitle from './utils/get-page-title'
// 白名单
const whiteList = ['/login', '/404']

// 路由前置守卫

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  nProgress.start()
  const token = store.state.user.token

  if (token) {
    // 已登录
    if (to.path === '/login') {
      next('/')
    } else {
      // 获取用户信息
      // await store.dispatch('user/getUserInfo')
      // 判断有没有用户信息
      if (!store.getters.userId) {
        // 没有就调用函数获取
        const menus = await store.dispatch('user/getUserInfo')
        // 根据后端返回的用户已经拥有的权限点从预置的八个动态路由中进行筛选路由
        // console.log(menus)
        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 动态添加路由
        router.addRoutes(filterRoutes)
        // 把动态路由添加到vuex中 生成左侧动态路由菜单
        store.commit('permission/setRoutes', filterRoutes)
        next({
          path: to.path,
          replace: true
        })
      }
      next()
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }

  // 手动隐藏进度条
  nProgress.done()
})

router.beforeEach((to, from, next) => {
  // console.log(to);
  document.title = getPageTitle(to.meta.title)
  next()
})

// 路由后置守卫

router.afterEach((to, from) => {
  nProgress.done()
})
